/**
 * 
 */
package com.java.test.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.java.test.system.dto.LoginAccountInfo;

@Component
public class TokenUtil {

	private static final String TOKEN_SECRET = "txdy"; // 密钥

	private static final long EXPIRE_TIME = 1000 * 60 * 90;

	/**
	 * 签名生成
	 * 
	 * @param user
	 * @return
	 */
	public static String sign(String userinfo) {
		String token = null;
		try {
			Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
			token = JWT.create().withIssuer("auth0").withClaim("userinfo", userinfo).withExpiresAt(expiresAt)
					// 使用了HMAC256加密算法。
					.sign(Algorithm.HMAC256(TOKEN_SECRET));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token;
	}

	/**
	 * 签名验证
	 * 
	 * @param token
	 * @return
	 */
	public static boolean verify(String token, HttpServletRequest request) {
		try {
			JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
			DecodedJWT jwt = verifier.verify(token);
			String userinfo = jwt.getClaim("userinfo").asString();
			if (userinfo == null || "".equals(userinfo))
				return false;
			LoginAccountInfo info = JsonUtil.json2obj(userinfo, LoginAccountInfo.class);

			if (info == null) {
				return false;
			}
			if (request != null) {
				String ipAddress = IpUtils.getIpAddress(request);
				info.setIp(ipAddress);
				request.getSession().setAttribute("user", info);
			}


			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static String getLoginUser(String token) {	
		JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
		DecodedJWT jwt = verifier.verify(token);
		String userinfo = jwt.getClaim("userinfo").asString();
		LoginAccountInfo info = JsonUtil.json2obj(userinfo, LoginAccountInfo.class);
		return info == null ? null : info.getLoginAccout();

	}

	public static String getBodyStringByReader(BufferedReader bufferedReader) {

		StringBuilder sb = new StringBuilder();
		try {
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
}
